<template>
  <div class="chat-container">
    <!-- 聊天内容显示区域 -->
    <div class="chat-box" ref="chatBox">
      <div v-for="(msg, index) in messages" :key="index" class="message-wrapper">
        <!-- AI 消息 -->
        <div v-if="msg.sender === 'ai'" class="message-row ai-row">
          <img src="../assets/image/deepseek-color.png" alt="AI头像" class="avatar" />
          <div class="message ai-message">
            <span v-if="msg.isTemp" class="loading-indicator">{{ msg.content }}</span>
            <span v-else v-html="msg.displayContent"></span>
          </div>
        </div>

        <!-- 用户消息 -->
        <div v-else-if="msg.sender === 'user'" class="message-row user-row">
          <div class="message user-message">{{ msg.content }}</div>
          <img src="../assets/image/yonghu.png" alt="用户头像" class="avatar" />
        </div>

        <!-- 系统消息 -->
        <div v-else class="message system-message">
          {{ msg.content }}
        </div>
      </div>
    </div>

    <!-- 输入框和按钮区域 -->
    <div class="input-box">
      <input
        v-model="inputMessage"
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
        type="text"
      />
      <button @click="sendMessage">发送</button>
      <button @click="closeConnection">关闭连接</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "ChatWindow",

  data() {
    return {
      inputMessage: "",
      messages: [],
      ws: null,
      clientId: Math.random().toString(36).substr(2),
      typingInterval: null, // 存储打字动画的定时器
      loadingMessageIndex: null, // 存储临时加载消息的索引
    };
  },

  mounted() {
    this.connectWebSocket();
  },

  methods: {
    connectWebSocket() {
      const wsUrl = `ws://localhost:8080/ws/${this.clientId}`;
      this.ws = new WebSocket(wsUrl);

      this.ws.onerror = () => {
        this.addMessage("system", "WebSocket 连接异常");
      };

      this.ws.onopen = () => {
        this.addMessage("system", "已连接");
      };

      this.ws.onmessage = (event) => {
        const message = event.data;

        if (!["连接成功", "close", "error"].includes(message)) {
          if (this.loadingMessageIndex !== null) {
            this.startTypingEffect(message);
            console.log("aaaaaaaaaaaaaaa")
          } else {
            this.addMessage("ai", message);
          }
        }
      };

      this.ws.onclose = () => {
        this.addMessage("system", "连接已关闭");
      };
    },

    sendMessage() {
      const message = this.inputMessage.trim();
      if (!message || !this.ws || this.ws.readyState !== WebSocket.OPEN) {
        alert("WebSocket 未连接或已关闭");
        return;
      }

      this.addMessage("user", message);
      this.ws.send(message);

      this.inputMessage = "";
      this.addLoadingMessage(); // 添加加载消息
      this.scrollToBottom();
    },

    addLoadingMessage() {
      const loadingMsg = { sender: 'ai', content: '正在思考', isTemp: true, displayContent: '' };
      this.messages.push(loadingMsg);
      this.loadingMessageIndex = this.messages.length - 1;

      let dotCount = 0;
      this.typingInterval = setInterval(() => {
        dotCount = (dotCount + 1) % 4;
        const dots = '.'.repeat(dotCount);
        this.messages[this.loadingMessageIndex].content = `正在思考${dots}`;
      }, 500);
    },

    startTypingEffect(fullText) {
      if (this.typingInterval) {
        clearInterval(this.typingInterval);
        this.typingInterval = null;
      }
      console.log("fullText", fullText);
      const paragraphs = fullText.split(/\n{1,2}/).filter(para => para.trim() !== '');
      console.log("paragraphs", paragraphs);
      const messageObj = this.messages[this.loadingMessageIndex];
      messageObj.displayContent = '';
      messageObj.isTemp = false;

      this.typeParagraph(paragraphs, 0, messageObj);
    },

    typeParagraph(paragraphs, index, messageObj) {
      if (index >= paragraphs.length) return;
      let charIndex = 0;
      const intervalId = setInterval(() => {
        if (charIndex < paragraphs.length) {
          messageObj.displayContent += paragraphs[charIndex]+'</br>';
          charIndex++;
        } else {
          clearInterval(intervalId);
        }
      }, 300); // 每个字符间隔 30ms
    },

    addMessage(sender, content) {
      this.messages.push({ sender, content, displayContent: content });
      this.scrollToBottom();
    },

    closeConnection() {
      if (this.ws) {
        this.ws.close();
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$refs.chatBox;
        chatBox.scrollTop = chatBox.scrollHeight;
      });
    },
  },

  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
    if (this.typingInterval) {
      clearInterval(this.typingInterval);
    }
  },
};
</script>
<style scoped>
.chat-container {
  max-width: 95%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 8px;
  height: 668px;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  font-family: Arial, sans-serif;
}

.chat-box {

  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #f0f2f5;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-bottom: 10px;
}

.message-wrapper {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.message-row {
  display: flex;
  align-items: start;
  margin-bottom: 10px;
}

.ai-row {
  justify-content: flex-start;
}

.user-row {
  justify-content: flex-end;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
  margin: 0 10px;
}

.message {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 10px;
  line-height: 1.4;
  word-break: break-word;
  position: relative;
  font-size: 14px;
}

.ai-message {
  background-color: #e9f5ff;
  color: #000;
  border: 1px solid #d0e7ff;
}

.user-message {
  background-color: #dcf8c6;
  color: #000;
  border: 1px solid #b2e1a1;
}

.loading-indicator {
  color: #666;
  font-weight: normal;
}

.input-box {
  display: flex;
}

.input-box input {
  flex: 1;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.input-box button {
  padding: 10px 15px;
  margin-left: 5px;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #007bff;
  color: white;
}

.input-box button:hover {
  background-color: #0056b3;
}

.system-message {
  align-self: center;
  background-color: #f1f1f1;
  color: #666;
  border: 1px solid #ccc;
  margin: 0 auto;
  font-style: italic;
}
</style>
